import yaml
import os
import smtplib
from email.mime.text import MIMEText

YAML_PATH = os.path.join(os.path.dirname(__file__), 'emailConfig.yaml')


class EmailInstant():
    def __init__(self):
        with open(YAML_PATH, 'r', encoding='utf-8') as f:
            result = yaml.load(f, Loader=yaml.FullLoader)
        self.emailHost = result['emailHost']
        self.emailUser = result['emailUser']
        self.emailAuth = result['emailAuth']
        self.receiver = result['receiver']

    def __str__(self):
        return ''' emailHost : {} 
            emailUser : {} 
            emailAuth : {} 
            receiver  : {}
        '''.format(self.emailHost, self.emailUser, self.emailAuth, self.receiver)


class EmailSender():
    def __init__(self):
        self.ins = EmailInstant()

        try:
            self.smtpObj = smtplib.SMTP()
            # 连接到服务器
            self.smtpObj.connect(self.ins.emailHost, 25)
            # 登录到服务器
            self.smtpObj.login(self.ins.emailUser, self.ins.emailAuth)
        except smtplib.SMTPException as e:
            print('error', e)  # 打印错误

    def send_email(self, raw_message: str):
        message = MIMEText(raw_message, 'plain', 'utf-8')
        # 邮件主题
        message['Subject'] = '标题'
        # 发送方信息
        message['From'] = self.ins.emailUser
        # 接受方信息
        message['To'] = self.ins.receiver

        self.smtpObj.sendmail(
            self.ins.emailUser, self.ins.receiver, message.as_string())

        print('success')

    def __del__(self):
        self.smtpObj.quit()


if __name__ == '__main__':
    e = EmailSender()
    # print(e)
    e.send_email('111')

